#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import os
import time
import matplotlib.pyplot as plt
import numpy as np
import sys
from plot2_iterationDecay import get_numLoadRun_fromScan
from os.path import join
import fileinput

def get_model_in_ldb_pct(filepath):
    ldbs = []
    fmodels = []
    with open(filepath) as f:
        lines = f.readlines()
        for line in lines:
            line = line[:-1]  # 去掉回车符号
            if '.' in line:
                if line.split('.')[1] == 'ldb':
                    ldbs.append(line)
                elif line.split('.')[1] == 'fmodel':
                    fmodels.append(line)

    num_alive_fmodels = 0
    for fmodel in fmodels:
        f_num = fmodel.split('.')[0]
        curresponding_ldb = (6-len(f_num))*'0' + f_num + '.ldb'
        if curresponding_ldb in ldbs:
            num_alive_fmodels = num_alive_fmodels + 1
    # 返回：fmodel的个数，有效的fmodel的个数， sstable的个数，具有fmodel的ldb占所有ldb的比例
    return len(fmodels), num_alive_fmodels, len(ldbs), float(num_alive_fmodels)/float(len(ldbs))


def get_fmodelPctDecay_4dataName(dataname, execultables, mds):
    pct_exe = dict()
    for executable in execultables:
        pct_md = dict()
        for md in mds:
            filedir = '../runlogs/' + dataname + '_' + executable + '_' + md + '/'
            # print('打印', filedir)

            l_fmodels = []
            num_alive_fmodels = []
            l_ldbs = []
            pcts = []

            for i in range(5):
                filename = 'iter' + str(i) + '.txt'
                l_fmodel, num_alive_fmodel, l_ldb, pct = get_model_in_ldb_pct(filedir + filename)

                l_fmodels.append(l_fmodel)
                num_alive_fmodels.append(num_alive_fmodel)
                l_ldbs.append(l_ldb)
                pcts.append(pct)
            pct_md[md] = {'num_fmodel': l_fmodels, 'num_alive_fmodels': num_alive_fmodels, 'num_ldb': l_ldbs, 'pcts': pcts}
        pct_exe[executable] = pct_md

    return pct_exe

# 2022、6、1 更新：自适应的cpu频率和操作数
ROOT = "../evaluation"


# 获取cpu频率，因为计时采用的是CPU周期
def get_cpu_ghz():
    for line in fileinput.input('/proc/cpuinfo'):
        if 'model name' in line:
            value = line.split('@ ')[1][:-1]
            digit = value[:-3]
            tag = value[-3:]
            if tag == "GHz":
                return float(digit)
            elif tag == "MHz":
                return float(digit) / 1000.0
            else:
                raise ValueError

cpu_freq_ghz = get_cpu_ghz()
S2US_FCTR = 1000000
K_FCTR = 1000
G_FCTR = 1000 * 1000 * 1000

# 计算操作延迟和秒千吞吐率
def circle_to_latencyInUs(num_circles, num_ops):
    """微秒延迟"""
    return ((num_circles * 2.6 / num_ops) / (cpu_freq_ghz * G_FCTR)) * S2US_FCTR

def kop_in_s(num_circles, num_ops):
    """秒千吞吐率"""
    return (1 / ((num_circles * 2.6 / num_ops) / (cpu_freq_ghz * G_FCTR))) / K_FCTR


def read_file(filename):
    lines = []
    with open(filename, 'r') as f:
        for line in f:
            if line.startswith("Timer 13") and (not line.startswith("Timer 13 MEAN")):
                lines.append(int(line.split(": ")[1].split('\n')[0]))

    return lines


# db_idf_758_19_random_put.txt
def get_perf_latency(dataname):
    expr_path = "../evaluation/expr_" + dataname + "_trace_realRun_16.txt"
    with open(expr_path) as f:
        lines = f.readlines()
    for line in lines:
        if "baseline latency" in line:
            baseline = eval(line.split("baseline latency: ")[1].split(" microseconds")[0])
        if "llsm (file) latency" in line:
            llsm = eval(line.split("llsm (file) latency: ")[1].split(" microseconds")[0])
    faster = baseline / llsm
    return faster


def plot_influence(datadir):
    WriteNumInLoads = []
    writeNumInRuns = []
    faster_ay = []
    filenames = os.listdir(datadir)
    plt.figure(figsize=(15, 10))

    for filename in filenames:
        dataname = filename.split('.')[0]
        numLoad, WriteNumInLoad, WritePctInLoad, numRun, ReadNumInRun, ReadPctInRun, writeNumInRun = get_numRun_and_ReadPctInRun(dataname)
        faster = get_perf_latency(dataname)

        WriteNumInLoads.append(WriteNumInLoad)
        writeNumInRuns.append(writeNumInRun)
        faster_ay.append(faster)

    plt.subplot(221)
    plt.scatter(WriteNumInLoads, writeNumInRuns, marker='o', s=(np.array(faster_ay)-1)*600)
    for i in range(len(WriteNumInLoads)):
        plt.text(WriteNumInLoads[i], writeNumInRuns[i], "%.2f" % faster_ay[i])
    plt.xlabel("Load WriteNum in M")
    plt.ylabel("Run writeNum in M")
    plt.xlim(3, 15)

    plt.subplot(222)
    plt.scatter(WriteNumInLoads, writeNumInRuns, marker='o', s=(np.array(faster_ay)-1)*600)
    for i in range(len(WriteNumInLoads)):
        plt.text(WriteNumInLoads[i], writeNumInRuns[i], "%.2f" % faster_ay[i])
    plt.xlabel("Load WriteNum in M")
    plt.ylabel("Run writeNum in M")
    plt.xlim(44, 48)


    plt.subplot(212)
    write_load_div_run = [WriteNumInLoads[i]/writeNumInRuns[i] for i in range(len(writeNumInRuns))]

    # 按列表a中元素的值进行排序，并返回元素对应索引序列
    sorted_id = np.argsort(write_load_div_run)
    plt.plot(np.array(write_load_div_run)[sorted_id], label='writeInLoad/writeInRun')
    plt.plot(np.array(faster_ay)[sorted_id], label="fasters")
    plt.legend()

    plt.savefig("../evaluation/influence.png")
    plt.show()


if __name__ == '__main__':
    datadir = "../ebs_segment_dataset/"
    plot_influence(datadir)
